package com.websocket.socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.google.gson.Gson;
import com.websocket.vo.ContentRecive;
import com.websocket.vo.Message;

@ServerEndpoint("/chatSocket")
public class ChatWebSocket {
	private String username;
	private static List<Session> session= new ArrayList<>();
	private static List<String> names=new ArrayList<>();
	private static Map<String, Session> map=new HashMap<>();
	
	@OnOpen
	public void open(Session session){
		String queryString=session.getQueryString();
		username=queryString.split("=")[1];
		System.out.println(username);
		
		this.session.add(session);
		this.names.add(username);
		this.map.put(this.username, session);
		
		String msg="欢迎" + this.username + "进入聊天室";
		
		Message message=new Message();
		message.setWelcome(msg);
		message.setUsername(this.names);
		
		this.broadcast(this.session,message.toJson());
		
	}
	
	private void broadcast(List<Session> ss, String jsonObject) {
		// TODO Auto-generated method stub
	    for(Iterator iterator=ss.iterator();iterator.hasNext();){
	    	Session session=(Session) iterator.next();
	    	try {
				session.getBasicRemote().sendText(jsonObject);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	}
	
	@OnClose
	public void close(Session session){
		this.session.remove(session);
		this.names.remove(username);
		
		String msg=this.username + "离开聊天室";
		Message message=new Message();
		message.setWelcome(msg);
		message.setUsername(this.names);
		
		this.broadcast(this.session, message.toJson());
	}
	
	private static Gson gson=new Gson();
	@OnMessage
    public void message(Session session,String json){
        
		ContentRecive cr = gson.fromJson(json, ContentRecive.class);
		
		if(cr.getType()==1){
			//广播
			Message message=new Message();
			message.setContent(this.username, cr.getMsg());
			
	    	this.broadcast(this.session, message.toJson());
		}else{
			//单聊
			//根据username 如果能找到 对应的session对象。
			String to=cr.getTo();
			Session to_session = this.map.get(to);
			Message message1=new Message();
			message1.setContent(this.username,"<font color=red >【私聊】" + cr.getMsg() + "</font>");
			
			try {
				to_session.getBasicRemote().sendText(message1.toJson());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    }
}
